package orb.transporte;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPTransport extends TransportAbstract {
	private TCPAddress address = new TCPAddress("localhost", 1500);

	
	
	public void setAddress(TCPAddress address) {
		this.address = address;
	}

	@Override
	public Buffer recieve() {
		byte[] resposta = new byte[512];
		try {
			ServerSocket recieverSocket = new ServerSocket(this.address.getPort());
			Socket connectionSocket = recieverSocket.accept();

			DataInputStream clientData = new DataInputStream(connectionSocket.getInputStream());

			int lido = 0;
			int i = 0;
			while ((lido = clientData.read()) != -1) {
				resposta[i] = (byte) lido;
				i++;
			}

			while (!recieverSocket.isClosed()) {
				recieverSocket.close();
				// connectionSocket.close();
				Thread.sleep(500);
			}

		} catch (IOException e) {
			System.out.println("Erro no envio de dados");
			e.printStackTrace();
		} catch (InterruptedException e) {
			System.out.println("Erro no sleep da thread");
			e.printStackTrace();
		}

		Buffer retorno = Buffer.getInstance();
		retorno.setData(resposta);
		return retorno;
	}

	@Override
	public void send(Buffer buffer) {

		try {
			Socket client = new Socket(this.address.getHost(), this.address.getPort());
			DataOutputStream out = new DataOutputStream(client.getOutputStream());

			out.write(buffer.getData());
			while (!client.isClosed()) {
				client.close();
				Thread.sleep(500);
			}

		} catch (UnknownHostException e) {
			System.out.println("Host desconhecido");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Erro no envio de dados");
			e.printStackTrace();
		} catch (InterruptedException e) {
			System.out.println("Erro no sleep da thread");
			e.printStackTrace();
		}

	}

}
